package com.example.books.ui.home;


import androidx.lifecycle.ViewModel;

import com.example.books.data.Book;
import com.example.books.data.Collection;

import org.litepal.LitePal;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HomeViewModel extends ViewModel {


    private int bid;

    /**
     *
     * @param bid 用户id
     */
    public void setBid(int bid) {
        this.bid = bid;
    }

    public HomeViewModel() {
        addBook();
    }

    public int getId(){
        return bid;
    }

    /**
     *
     * @param b
     * @return 收藏提示文字
     */
    public String getTrue(Boolean b){
        String s ="";
        if(b){
            s="收藏成功";
        }else {
            s="已收藏";
        }
        return s;
    }

    /**
     *
     * @return 此用户收藏书id数组
     */
    public Long[] getB(){
        List<Collection> all = LitePal.select("bookId").where("userId=?",getId()+"").find(Collection.class);
        Long[] i=new Long[all.size()];
        int a=0;
        for (Collection c : all) {
            i[a]=c.getBookId();
        }
        return i;
    }

    /**
     * 书城数据
     * @return
     */
    public List<Book> getallB(){
        final List<Book> allB = LitePal.findAll(Book.class);
        return allB;
    }

    /**
     * 搜索功能
     * @param s 关键词
     * @return 相匹配数据
     */
    public Set<Book> getallS(String s){
        Set<Book> all=new HashSet<>();
        final List<Book> allB = LitePal.findAll(Book.class);
        for (Book a:allB){
            if(a.getBookAuthor().contains(s)){all.add(a);}
            if(a.getBoolkName().contains(s)){all.add(a);}
        }
        return all;
    }

    /**
     * 添加书本数据
     */
    private void addBook() {
        Book book = new Book();
        book.setBookpath("绝望黎明.txt");
        book.setBookAuthor("宁采成");
        book.setBoolkName("绝望黎明");
        book.save();
        book = new Book();
        book.setBookpath("异界之魔武流氓.txt");
        book.setBoolkName("异界之魔武流氓");
        book.save();
    }

}